import { useRef, useState } from 'react';
import { createContainer } from 'unstated-next';

import useMergedState from 'rc-util/lib/hooks/useMergedState';
import { BasicColums, BasicTableProps } from './types/table';

export type ColumnsState = {
  show?: boolean;
  fixed?: 'left' | 'right' | boolean;
  order?: number;
};

export type ColumnsStateMap = Record<string, ColumnsState>;

export type UseContainerProps<T> = {
  columnsStateMap?: ColumnsStateMap;
  onColumnsStateChange?: (map: Record<string, ColumnsState>) => void;
  columns?: BasicColums<T>[];
};

function useContainer<T>(props: UseContainerProps<T> = {}) {
  // 原始数据存放
  const basicPropsRef = useRef<BasicTableProps<any>>();

  //
  const basicColumnsData = useRef<BasicColums<T>[]>(props.columns || []);

  // const [columnsStateMap, setColumnsStateMap] = useMergedState<
  //   Record<string, ColumnsState>
  // >(props.columnsStateMap || {}, {
  //   value: props.columnsStateMap,
  //   onChange: (val) => {
  //     props.onColumnsStateChange && props.onColumnsStateChange(val);
  //   },
  // });

  const [columnsStateMap, setColumnsStateMap] = useState<
    Record<string, ColumnsState>
  >(props.columnsStateMap || {});

  const setBasicPropsRef = (val: BasicTableProps<any>) => {
    basicPropsRef.current = val;
  };

  return {
    columnsStateMap,
    setColumnsStateMap: (val: ColumnsStateMap) => {
      setColumnsStateMap(val);
      props.onColumnsStateChange && props.onColumnsStateChange(val);
    },
    basicPropsRef,
    setBasicPropsRef,
    basicColumnsData,
  };
}

const Container = createContainer<
  ReturnType<typeof useContainer>,
  UseContainerProps<any>
>(useContainer);

export type ContainerType = typeof useContainer;

export { useContainer };

export default Container;
